package com.tangtangtang.gulimall.thirdpaty.TencentUtils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.Bucket;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 初级的腾讯与你的Cos的使用
 */
@Component
public class TencentOss {
    //腾讯云的密钥id
    @Value("${tencent.secretld}")
    private String secretld;
    //腾讯云的密钥key
    @Value("${tencent.secretkey}")
    private String secretkey;
    //腾讯云服务器位置
    @Value("${tencent.rogin}")
    private String rogin;
    //腾讯云对象存储存储桶名称
    @Value("${tencent.bucket}")
    private String bucket;

    public COSClient getCosClient()
    {
        //1.初始化身份信息
        COSCredentials cosCredentials = new BasicCOSCredentials(secretld,secretkey);
        //2.确定地域
        Region region = new Region(rogin);
        ClientConfig clientConfig = new ClientConfig(region);
        //3.创建COS客户端
        COSClient cosClient = new COSClient(cosCredentials,clientConfig);
        return cosClient;
    }

    //查询当前腾讯云对象存储桶
    public void getTencentCosClientBucket()
    {
        //调用当前文件cosClient
        COSClient cosClient = this.getCosClient();
        List<Bucket> listBuckets = cosClient.listBuckets();
        for (Bucket bucket:listBuckets) {
            System.out.println(bucket);
        }
    }

    //文件上传(这个的上传没有验证签名，最大上传只有5个G)
    public String uploadFiletobucket(String path)
    {
        COSClient cosClient = this.getCosClient();
        try{
            File tobucketfile = new File(path);
            System.out.println(tobucketfile);
            String suffix = path.substring(path.lastIndexOf(".")+1);
            System.out.println("后缀名称为："+suffix);
            //指定文件名称的对象键，使用一个uuid
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String filekey = uuid+"."+suffix;//形成一个新的上传文件名称
            System.out.println(filekey);
            //将文件进行上传，共有三个参数，第一个腾讯云存储对象名称，第二个是在bucket里面存储的名称，第三个文件路径
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucket,filekey,tobucketfile);
            PutObjectResult putObjectResult =  cosClient.putObject(putObjectRequest);
            System.out.println("处理结果："+putObjectResult);
            //上传完成进行关闭
            cosClient.shutdown();
        }catch (Exception e){
            e.printStackTrace();
            return "lose";
        }
        return "success";
    }
}
